import router from "../router";
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { message } from 'ant-design-vue'
import { checkAccess } from '@/utils'
import { whiteRouteList } from '@/config'

// 是否为首次获取登录用户
let isFirstGetLoginUser = true;

/**
 * 全局权限校验
 */
router.beforeEach(async (to, from, next) => {
  // 如果是白名单路由，直接放行
  if (whiteRouteList.includes(to.path)) {
    next()
    return
  }

  const loginUserStore = useLoginUserStore();
  let loginUser = loginUserStore.loginUser;
  // 确保页面刷新，首次加载时，能够等后端返回用户信息后再校验权限
  if (isFirstGetLoginUser) {
    await loginUserStore.fetchLoginUser();
    loginUser = loginUserStore.loginUser;
    isFirstGetLoginUser = false;
  }
  // 权限标识
  const access = to.meta?.access ?? "";
  // 如果存在权限标识 && 校验权限失败
  if (access && !checkAccess(loginUser, access)) {
    message.error('没有权限')
    next(`/login?redirect=${to.fullPath}`)
    return
  }
  next()
})
